/*
DATE：2016-10-12

settings 参数说明
-----
url -----------------------------数据请求地址
params --------------------------请求参数,json对象或k1=v1&k2=v2&k3=v3格式
success -------------------------表格渲染成功后回调方法
checkEvent ----------------------选择框change事件
selectedRows --------------------返回选中对应行数据
------------------------------ */
(function($){
	$.fn.gcDataGrid=function(opt){
		var $table = $(this);
		// 默认值
		opt=$.extend({
			url:'',
			data:null,
			params:{},
			trId:'',
			pageNO:1,
			pageSize:15,
			selectedRows:[],
			selectedAll:[],
			pageBar:function(){},
			success:function(){},
			checkEvent:function(){}
		},opt);
		
		var init=function(respData){
			$table.find('tbody').remove();
			
			var $tableTH = $table.find('thead th');
			
			var bodyTR = '<tbody>';
			
			var dataRows = respData.rows;
			if(dataRows == undefined && (respData instanceof Array)){
				dataRows = respData;
			}

			if(dataRows.length > 0) {
				//渲染表格数据
				$.each(dataRows, function (i, row) {
					var trId = '';
					if(!isEmpty(opt.trId) && !isEmpty(row[opt.trId])){
						trId = 'g_id="'+row[opt.trId]+'"';
					}
					bodyTR += '<tr '+trId+'>';
					$tableTH.each(function (j) {
						var thName = $(this).attr('name');
						var className = $(this).attr('td-class');   //设置td的class
						var isTitle = $(this).attr('td-title');     //设置td的title展示原值
						var isTitleFmt = $(this).attr('td-titleFmt'); //设置td的title展示格式后的值
						var attr = $(this).attr('td-attr');
						var tdVal = row[thName];
						var title = '';

						if(className == undefined || className == null){
							className = '';
						}
						if(className.indexOf('td_nowrap') >= 0){
							title = tdVal;
						}
						if(isTitle=='true'){
							title = tdVal;
						}

						var serialNO = (parseInt(opt.pageNO)-1)*parseInt(opt.pageSize)+(i + 1);

						if ($(this).attr('columnType') == 'checkbox') {
							tdVal = '<input type="checkbox" name="' + thName + '" value="' + tdVal + '">';
						} else if ($(this).attr('columnType') == 'checkbox_serial') {
							tdVal = '<input type="checkbox" name="' + thName + '" value="' + tdVal + '" id="ckb_' + serialNO + '"><label for="ckb_' + serialNO + '" class="input-all">' + serialNO + '</label>';
						} else if ($(this).attr('columnType') == 'radio') {
							tdVal = '<input type="radio" name="' + thName + '" value="' + tdVal + '">';
						} else if ($(this).attr('columnType') == 'radio_serial') {
							tdVal = '<input type="radio" name="' + thName + '" value="' + tdVal + '" id="ckb_' + serialNO + '"><label for="ckb_' + serialNO + '" class="input-all">' + serialNO + '</label>';
						} else if ($(this).attr('columnType') == 'serial') {
							tdVal = serialNO;
						} else {
							var funName = $(this).attr('customFormat');
							try {
								if (funName) {
									var fun = eval(funName);
									tdVal = fun(row[thName], row, thName);
									if(isTitleFmt=='true'){
										title = tdVal;
									}
								}
							} catch (e) {

							}
							if (isEmpty(tdVal)) {
								tdVal = '--';
							}
						}

						if(!isEmpty(title)){
							title = 'title="'+title+'"';
						}
						if(isEmpty(attr)){
							attr = '';
						}else{
							try{
								var attrJson = eval( "(" + attr + ")" );
								attr = '';
								$.each(attrJson, function(k,v){
									attr += k + '="'+v+'"';
								})
							}catch (e){
								console.log(e.message);
							}
						}
						if(isEmpty(thName)){
							thName = '';
						}
						bodyTR += '<td name="' + thName + '" class="'+className+'" '+title+ attr + '>' + tdVal + '</td>';
					})
					bodyTR += '</tr>';
				})
			}else{
				bodyTR += '<tr><td colspan="'+$tableTH.length+'" style="text-align: center">暂无数据</td></tr>';
			}

			bodyTR += '</tbody>'
			$table.find('thead').after(bodyTR);
			
			if($tableTH.eq(0).attr('columnType') == 'checkbox' || $tableTH.eq(0).attr('columnType') == 'checkbox_serial'){
				$table.find('tr input[type=checkbox]').iCheck({
				    checkboxClass: 'icheckbox_square-red',//iradio_square-red
				    radioClass: 'icheckbox_square-red'
				});
			}else if($tableTH.eq(0).attr('columnType') == 'radio' || $tableTH.eq(0).attr('columnType') == 'radio_serial'){
				$table.find('tr input[type=radio]').iCheck({
					checkboxClass: 'iradio_square-red',
				    radioClass: 'iradio_square-red'
				});
			}

			$table.off('change','th[columnType=checkbox] input[type=checkbox], th[columnType=checkbox_serial] input[type=checkbox]');
			$table.off('change','td[name='+$tableTH.eq(0).attr('name')+'] input');

			//全选
			$table.on('change','th[columnType=checkbox] input[type=checkbox], th[columnType=checkbox_serial] input[type=checkbox]',function(){
				$th = $(this).parents('th');
				if($(this).prop('checked')){
					$table.find('td[name='+$th.attr('name')+'] input[type=checkbox]').iCheck('check');
				}else{
					$table.find('td[name='+$th.attr('name')+'] input[type=checkbox]').iCheck('uncheck');
				}
				var checked = $(this).prop('checked');
				selected($tableTH, dataRows,checked,dataRows);
			})
			
			$table.on('change','td[name='+$tableTH.eq(0).attr('name')+'] input',function(){
				var uncheckedSize = $table.find('td[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').not("input:checked").length;
				if(uncheckedSize > 0){
					$table.find('th[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').iCheck('uncheck');
				}else{
					$table.find('th[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').iCheck('check');
				}

				var checked = $(this).prop('checked');
				var index = $(this).parents('tbody').children('tr').index($(this).parents('tr'));
				var curRow = dataRows[index];
				selected($tableTH, dataRows ,checked,curRow);
			})
			
			if($table.next('.checked_cnt').length == 0){
				$table.after('<div class="checked_cnt" style="display: none"></div>')
			}
			//勾上存在的值
			$table.next('.checked_cnt').find('.checked_item').each(function(){
				$table.find('td input[value='+$(this).attr('data-id')+']').iCheck('check');
			});
			//设置是否全选
			var uncheckedSize = $table.find('td input[type=checkbox]').not("input:checked").length;
			if (uncheckedSize > 0) {
				$table.find('th input[type=checkbox]').iCheck('uncheck');
			} else if($table.find('td input[type=checkbox]').length > 0){
				$table.find('th input[type=checkbox]').iCheck('check');
			}

			opt.pageBar.call($table, respData);
			opt.success.call($table, respData);

		};
		
		//设置选择的数据
		var selected=function($tableTH, dataRows,checked,curRow){
			opt.selectedRows=[];
			opt.selectedAll=[];
			$table.find('td[name='+$tableTH.eq(0).attr('name')+'] input:checked').each(function(){
				var index = $(this).parents('tbody').children('tr').index($(this).parents('tr'));
				opt.selectedRows.push(dataRows[index]);
			})
			$table.next('.checked_cnt').find('.checked_item').each(function(){
				opt.selectedAll.push($(this).attr('data-id'));
			})
			opt.checkEvent.call($table, opt.selectedRows, checked, curRow);
		};
		
		//加载数据
		var loadData=function(){
			if(opt.data != undefined && opt.data != null && opt.data.length > 0){
				init(opt.data);
			}else if(opt.url != undefined && opt.url != null && opt.url != ''){
				$.ajax({
					type:'post',
					url:opt.url,
					data:opt.params,
					dataType:'json',
					success:function(resp){
						init(resp);
					}, error: function (request) {
						layer.alert('操作失败', {icon: 0});
					}
				})
			}

		}

		//判断字符串是否为空
		function isEmpty(s) {
			return ((s == undefined || s == null || s === '') ? true : false);
		}

		loadData();
		
		return opt;
	};
})(jQuery);